package com.jinzhi.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;

import com.aliyun.oss.model.PutObjectResult;
import com.jinzhi.common.exception.IFastException;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.ConstantPropertiesUtil;
import com.jinzhi.oss.service.OssService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 上传阿里云OSS实现类
 */
@Service
@AllArgsConstructor
@Slf4j
public class OssServiceImpl implements OssService {


    @Override
    public String uploadFileOss(MultipartFile file) {
        //地域节点
        String endpoint = ConstantPropertiesUtil.END_POINT;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String bucketPath = ConstantPropertiesUtil.BUCKET_PATH;

        try {
            // 创建OSSClient2.8.3实例
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            //添加一个UUID值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //拼接到filename前面
            filename =uuid+filename;

            //2019/11/17/01.jpg
            //获取当前日期，转换/2019/11/17
            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy/MM/dd");
            String timeUrl = simpleDateFormat.format(new Date());
            filename =timeUrl+"/"+filename;
            try {
                ossClient.putObject(bucketName, filename, inputStream);
                log.info("阿里云上传文件成功，bucketName:{},key:{},url:{}", bucketName, accessKeyId, bucketPath);
        }catch(Exception e) {
                log.warn("阿里云上传文件失败：{},bucketName:{},key:{}", e.getMessage(), bucketName, accessKeyId);
            throw new IFastException(EnumErrorCode.FileUploadError.getCodeStr());
        }finally {
            ossClient.shutdown();
        }
            //返回上传之后url地址--例如： https://guli-edu-191117.oss-cn-beijing.aliyuncs.com/7.jpg
            String url = "https://" + bucketPath + "/" + filename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String uploadUrlFileOss(MultipartFile file, String url) {
        //地域节点
        String endpoint = ConstantPropertiesUtil.END_POINT;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String bucketPath = ConstantPropertiesUtil.BUCKET_PATH;

        try {
            // 创建OSSClient2.8.3实例
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            //严重阿里云OSS是否存在这个文件
            boolean  foo=  ossClient.doesObjectExist(bucketName,url);
                if(foo){
                    String url1 = "https://" + bucketPath + "/" + url;
                    return url1;
                }
            //添加一个UUID值
           // String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //拼接到filename前面
           // filename =uuid+filename;

            //2019/11/17/01.jpg
            //获取当前日期，转换/2019/11/17
            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy/MM/dd");
            String timeUrl = simpleDateFormat.format(new Date());
            filename =url;
            try {
                ossClient.putObject(bucketName, filename, inputStream);
                log.info("阿里云上传文件成功，bucketName:{},key:{},url:{}", bucketName, accessKeyId, bucketPath);
            }catch(Exception e) {
                log.warn("阿里云上传文件失败：{},bucketName:{},key:{}", e.getMessage(), bucketName, accessKeyId);
                throw new IFastException(EnumErrorCode.FileUploadError.getCodeStr());
            }finally {
                ossClient.shutdown();
            }
            //返回上传之后url地址--例如： https://guli-edu-191117.oss-cn-beijing.aliyuncs.com/7.jpg
            String url1 = "https://" + bucketPath + "/" + filename;
            return url1;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }
//
//    public static String upload(String bucketName, String key, InputStream input) {
//        if(StringUtils.isBlank(bucketName) || StringUtils.isBlank(key) || input==null) {
//           throw new IFastException(EnumErrorCode.FileUploadError.getCodeStr());
//        }
//
//        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//        try {
//            ossClient.putObject(bucketName, key, input);
//            Date expiration = DateUtils.addYears(new Date(), 10); // 设置URL过期时间为10年
//            String url = ossClient.generatePresignedUrl(bucketName, key, expiration).toString();
//            log.info("阿里云上传文件成功，bucketName:{},key:{},url:{}", bucketName, key, url);
//           return url;
//        }catch(Exception e) {
//            log.warn("阿里云上传文件失败：{},bucketName:{},key:{}", e.getMessage(), bucketName, key);
//            throw new IFastException(EnumErrorCode.FileUploadError.getCodeStr());
//        }finally {
//            ossClient.shutdown();
//        }
//
//    }
}
